package com.twang.stock.service.jinyan;

import com.twang.stock.entity.CompanyCodeInfo;
import com.twang.stock.entity.StockInfo;
import com.twang.stock.mapper.CompanyCodeInfoMapper;
import com.twang.stock.mapper.StockInfoMapper;
import com.twang.stock.service.impl.MinutesVolRuleService;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 计算涨跌
 */
@Slf4j
@Service
public class JiSuanZhangDieService {

    @Resource
    private StockInfoMapper stockInfoMapper;

    @Autowired
    private MinutesVolRuleService minutesVolRuleService;

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;


    public void update() {
        List<CompanyCodeInfo> stockList = companyCodeInfoMapper.selectAll();
        stockList.forEach(item -> {
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                Example example = new Example(StockInfo.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andIsNull("zhangdie");
                criteria.andEqualTo("code", item.getCompanyCode());
                example.orderBy("date").desc();
                List<StockInfo> resultList = stockInfoMapper.selectByExample(example);
                log.info(" size={}", resultList.size());
                resultList.forEach(info -> {
                    asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                        updateHznagDie(info);
                    });
                });
            });
        });
    }


    private void updateHznagDie(StockInfo item) {
        //上一交易日
        StockInfo stockInfoYesterDay = minutesVolRuleService.getCode(item.getCode(), item.getDate());
        if (null == stockInfoYesterDay) {
            return;
        }
        item.setZhangdie(((item.getPrice().subtract(stockInfoYesterDay.getPrice())).divide(stockInfoYesterDay.getPrice(), 5, BigDecimal.ROUND_HALF_UP)).multiply(new BigDecimal(100)));
        stockInfoMapper.updateByPrimaryKey(item);
    }
}
